<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Requests\Api\RegisterRequest;
use App\Http\Requests\Api\ResetRequest;
use App\Models\User;
use Carbon\Carbon;

class RegisteController extends Controller
{
    public function store(RegisterRequest $request)
    {
        //校验验证码
        $email_key = $request->email_key;
        $emailCodeData = \Cache::get($email_key);

        if(!$emailCodeData) {
            return $this->response->error('邮箱验证码已经过期',422);
        }

        if($emailCodeData['email'] != $request->email) {
            return $this->response->error('输入邮箱和接受邮箱不相同',422);
        }

        if(!hash_equals($emailCodeData['code'],$request->email_code)) {
            //验证码错误就清除
            \Cache::forget($request->captcha_key);
            return $this->response->errorUnauthorized('验证码错误');
        }

        $user = User::create([
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'name' => $request->name,
            'email_verified_at' =>  now(),
        ]);

        if(empty($user)) {
            return $this->response->errorUnauthorized('注册失败');
        }

        $token = \Auth::guard('api')->attempt([
            'email' => $request->email,
            'password' => $request->password,
        ]);

        return $this->respondWithToken($token);
    }

    public function reset(ResetRequest $request, User $user)
    {
        //校验验证码
        $email_key = $request->email_key;
        $emailCodeData = \Cache::get($email_key);

        if(!$emailCodeData) {
            return $this->response->error('邮箱验证码已经过期',422);
        }

        if($emailCodeData['email'] != $request->email) {
            return $this->response->error('输入邮箱和接受邮箱不相同',422);
        }

        if(!hash_equals($emailCodeData['code'],$request->email_code)) {
            //验证码错误就清除
            \Cache::forget($request->captcha_key);
            return $this->response->errorUnauthorized('验证码错误');
        }
        $userInfo = $user->where('email','=', $request->email)->first();
        $user = $userInfo->update([
            'password' => bcrypt($request->password),
        ]);

        if(empty($user)) {
            return $this->response->errorUnauthorized('重置失败');
        }

        $token = \Auth::guard('api')->attempt([
            'email' => $request->email,
            'password' => $request->password,
        ]);

        return $this->respondWithToken($token);
    }

    protected function respondWithToken($token)
    {
        return $this->response->array([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
        ]);
    }
}
